interface TreeNode {
	title: string;
	key: string;
	children?: TreeNode[];
	isLeaf?: boolean;
}

// 添加或移除 HTML 元素的类名
export function toggleHtmlClass(className: string) {
	/**
	 * 添加类名到 HTML 元素
	 */
	function add() {
		document.documentElement.classList.add(className);
	}

	/**
	 * 从 HTML 元素移除类名
	 */
	function remove() {
		document.documentElement.classList.remove(className);
	}

	return {
		add,
		remove
	};
}

// 获取对象的所有键，支持嵌套对象
export function getKeys<T extends Record<string, unknown>>(
	obj: T,
	parentKeys: string[] = []
): string[] {
	let keys: string[] = [];

	for (const key in obj) {
		if (Object.hasOwn(obj, key)) {
			const newKeys = [...parentKeys, key];
			const value = obj[key];
			// 如果值是对象且不为 null，递归获取键
			if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
				keys = keys.concat(getKeys(value as Record<string, unknown>, newKeys));
			} else {
				keys.push(key);
			}
		}
	}

	return keys;
}

export const getTestData = <T>(data: T, len: number): T[] => {
	const arr: T[] = [];
	for (let i = 0; i < len; i++) {
		arr.push(data);
	}
	return arr;
};

export function isImageUrl(url: string) {
	if (!url) return false;
	// 匹配最后一个点后的扩展名（忽略查询参数和哈希值）
	const extMatch = url.match(/\.([^./?#]+)(?:[?#]|$)/i);
	if (!extMatch) return false;

	const ext = extMatch[1].toLowerCase();
	const imageExtensions = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'webp', 'svg'];

	return imageExtensions.includes(ext);
}
/**
 * 将扁平数组转为树结构，并生成符合 antd Tree 的数据结构
 */

export const arrToTree1 = (data: any[], rootName = '根目录') => {
	// Step 1: 构建 id -> item 映射
	const map = {};
	const tree: any = [];

	data.forEach(item => {
		map[item.id] = { ...item, children: [] };
	});

	// Step 2: 构建树结构
	data.forEach(item => {
		const node = map[item.id];
		if (item.parentId && map[item.parentId]) {
			map[item.parentId].children.push(node);
		} else {
			tree.push(node);
		}
	});

	// Step 3: 转为 Antd Tree 结构（带 title、key、isLeaf）
	const convertToTreeNode = (nodes, path = '0-0') =>
		nodes.map((node, index) => {
			// const key = `${path}-${index}`;
			const key = node.id;
			const children = node.children?.length ? convertToTreeNode(node.children, key) : [];

			return {
				title: node.name,
				key,
				isLeaf: children.length === 0,
				remark: node.remark,
				data: node,
				children: children.length > 0 ? children : undefined
			};
		});

	return [
		{
			title: rootName,
			key: 'root',
			children: convertToTreeNode(tree, 'root')
		}
	];
};

const cacheMap = new Map();
export function strToArr(str?: string) {
	if (str) {
		if (cacheMap.has(str)) {
			return cacheMap.get(str);
		}
		const result = str.split(',');
		cacheMap.set(str, result);
		return result;
	}
	return [];
}

export function strToArrImg(str?: string) {
	if (str) {
		if (cacheMap.has(str)) {
			return cacheMap.get(str);
		}
		const result = str.split(',').map((item, key) => {
			return { url: item, id: key, status: 'done' };
		});
		cacheMap.set(str, result);
		return result;
	}
	return [];
}
